import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './home/index.dart';
import './message/index.dart';
import './mine/index.dart';

class HomePage extends StatefulWidget {
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  var _tabController;
  var intIndex = 0;
  final titleArr = ['首页', '消息', '个人中心'];
  final tabArr = <StatefulWidget>[
    new TabHome(),
    new TabMessage(),
    new TabMine()
  ];

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 4, vsync: this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    // new Future.delayed(const Duration(seconds: 3),(){
    //   print('Duration');
    //   Navigator.pushReplacementNamed(context,LoginPage.sName);
    // });
    this.checkoutLogin();
  }

  /// 检查登录状态
  void checkoutLogin() async{
    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
    final SharedPreferences prefs = await _prefs;
    final String userInfo = prefs.getString('userInfo') ?? null;
    if (userInfo == null) {
      Navigator.pushReplacementNamed(context, 'login');
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(this.titleArr[intIndex]),
        centerTitle: true,
        bottom: new TabBar(
          controller: _tabController,
          tabs: <Widget>[
            Icon(IconData(0xe867, fontFamily: 'iconfont'),color: Colors.orange,size: 24.0),
            Icon(IconData(0xe84a, fontFamily: 'iconfont'),color: Colors.orange,size: 24.0),
            Icon(IconData(0xe7b1, fontFamily: 'iconfont'),color: Colors.orange,size: 24.0),
          ]
        ),
      ),
      body: tabArr[this.intIndex],

      bottomNavigationBar: new BottomNavigationBar(items: [
        new BottomNavigationBarItem(
          icon: Icon(IconData(0xe867, fontFamily: 'iconfont'),size: 24.0),
          title: new Text("首页"),
          backgroundColor: Colors.grey,
        ),
        new BottomNavigationBarItem(
          icon: Icon(IconData(0xe84a, fontFamily: 'iconfont'),size: 24.0),
          title: new Text("消息"),
          backgroundColor: Colors.grey,
        ),
        new BottomNavigationBarItem(
          icon: Icon(IconData(0xe7b1, fontFamily: 'iconfont'),size: 24.0),
          title: new Text("我的"),
          backgroundColor: Colors.grey,
        )
      ],
        onTap: onTap,
        currentIndex: intIndex
      )
    );
  }

  void onTap(int index) async{
    setState(() {
      this.intIndex = index;
    });
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    await prefs.setInt('counter', counter);
    print('Pressed $counter times.');
  }
}
